import { sleep } from "@/utils";
import IpcParams from "../IpcParams";
import { createAgent } from './utils';
import Axios from 'axios';
import axiosRetry from 'axios-retry';
const stringUtil = require('@/utils/string')
import DexieCtx from '@/utils/dexiectx';


export default class CowsGame {
  constructor(tokenInfo) {
    this.tokenInfo = tokenInfo
    const agent = createAgent(this.tokenInfo.proxy)
    const headers = {
      "Content-Type": "application/json",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
    }
    this.dexie = DexieCtx.db()
    this.axios = Axios.create({
      headers: headers,
      httpAgent: agent,
      httpsAgent: agent,
      timeout: 90 * 1000,
    })
    axiosRetry(this.axios, {
      retries: 5, retryDelay: (retryCount) => {
        return 2000
      }
    });
  }

  async run() {
    try {
      
      let webSessionUrl = this.tokenInfo.tgweb
      if (webSessionUrl.startsWith("https://") == false) {
        // console.error(`${this.gameInfo.phone}  error session url ${webSessionUrl}`);
        return
      }
      webSessionUrl = decodeURIComponent(webSessionUrl)
      let session = webSessionUrl.split("#tgWebAppData=")[1]
      session = session.split("&tgWebAppVersion")[0]
      // const headers = {
      //   authorization: "tma " + session,
      // }

      const login_body = {
        initData: session,
        invite: ""
      }

      const inviteUrl = this.tokenInfo.inviteUrl
      let refId = 0
      if (inviteUrl != null) {
        refId = inviteUrl.split("startapp=")[1]
        refId = parseInt(refId)
      }
      // 登录
      let access_token = ''
      await this.axios.post('https://app.tonmeme.xyz/api/user/login', login_body, {
        'headers': {
          'Content-Type': 'application/json',
        }
      }).then(response => {
        access_token = response.data.token
      }).catch(function (error) {
        console.log(error)
      })

      const headers = {
        'Content-Type': 'application/json',
        Token: access_token,
      }

      console.log(headers)

      // fetch active activities
      const activities = []
      await this.axios.get('https://app.tonmeme.xyz/api/action/active', {
        'headers': headers
      }).then(response => {
        response.data.data.forEach((taskValue, taskKey) => {
          console.log(taskValue.action)
          activities.push(taskValue)
        })
      }).catch(function (error) {
        console.log(error)
      })

      const activity_random = stringUtil.getRandomIntInclusive(0, activities.length)
      console.log("activity_random  -----------------------    : ", activity_random)

      const activity = activities[activity_random]
      const action_body = {
        "action": activity.action,
        "status":1,
        "data":""
      }

      console.log('action_body    : ', action_body)
      await this.axios.post('https://app.tonmeme.xyz/api/action/update', action_body ,{
        'headers': headers
      }).then(response => {
        console.log( response )
        // console.log('response data : ', response.data[0].data.telegramUserLogin.access_token)
        // access_token = response.data
      }).catch(function (error) {
        console.log(error)
      })

      // get balance again
      let user_balance = ''
      await this.axios.post('https://app.tonmeme.xyz/api/user/login', login_body, {
        'headers': {
          'Content-Type': 'application/json',
        }
      }).then(response => {
        // console.log('-------------------------CREDIT  22--------------------------')
        // console.log(response.data.data.credit.credit)
        // console.log('-------------------------CREDIT  22--------------------------')

        user_balance = response.data.data.credit.credit
      }).catch(function (error) {
        console.log(error)
      })


      console.log('user_balance : ',user_balance)

      this.tokenInfo.score = user_balance
      const date = (new Date()).toLocaleString()
      this.tokenInfo.gameupdate = date
      this.tokenInfo.count = (this.tokenInfo.count || 0) + 1

      // console.log(date, "cows end", this.tokenInfo.phone, "score: ", this.tokenInfo.score)

      if ( user_balance > 0 ) {
        await this.dexie.cows.where('phone').equals(this.tokenInfo.phone).modify({
          score: user_balance,
          gameupdate: (new Date()).toLocaleString(),
        })
      }
      
      console.log("this.tokenInfo ::::   ", this.tokenInfo)

      return new IpcParams("runCows", this.tokenInfo)
    } catch (error) {
      console.log(error)
      // console.log((new Date()).toLocaleString(), "cows error", this.gameInfo.phone)
      if (error.response) {
        console.error(error.request.path, error.response)
      } else {
        console.error(error)
      }
      return new IpcParams("runCows", this.tokenInfo, error)
    }
  }
}
